<?php namespace FoxLib\Services;

use Illuminate\Support\Facades\Log;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;

class LogService extends AbstractProcessingHandler
{
    /**
     * Writes the record down to the log of the implementing handler
     *
     * @param  array $record
     * @return void
     */
    protected function write(array $record)
    {
        if ($record['level'] >= Logger::toMonologLevel(config('logging.channels.aliyun.level'))) {
            app('logContext')->setItem($record);
        }
    }

    public static function push()
    {
        $items = app('logContext')->getItems();
        if (count($items)) {
            try {
                $project = config('aliyun.log_project');
                $store = config('aliyun.log_store');
                $topic = config('aliyun.log_topic');
                $endpoint = config('aliyun.log_endpoint');
                $accessKeyId = config('aliyun.access_key_id');
                $accessKeySecret = config('aliyun.access_key_secret');
                $client = new \Aliyun_Log_Client($endpoint, $accessKeyId, $accessKeySecret);
                $request = new \Aliyun_Log_Models_PutLogsRequest($project, $store, $topic, '', $items);
                $client->putLogs($request);
            } catch (\Aliyun_Log_Exception $e) {
                Log::warning('[AliyunLog]' . $e->getErrorCode() . $e->getErrorMessage());
            }
        }
    }
}

